<?php

class Admin_TreeController extends Zend_Controller_Action
{
    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // action body
    }
    public function childrenAction()
    {
    	$m = new Admin_Model_TreeNodeMapper();
    	$nodes = null;
    	$pId = (int)$this->getRequest()->getParam('pId',0);
    	if ($pId>0)
    	{
    		$nodes = $m->fetchChildrens($pId,true);
    	}
    	$this->_helper->json ( $nodes );
    }
    public function loadEditorAction()
    {
    	$req = $this->getRequest();
    	$id = ( int ) $req->getParam ( 'id', 0 );
		$m1 = new Admin_Model_TreeNodeMapper( );
		$m2 = new Admin_Model_NodeConfigMapper ( );
		
		$node = $m1->find($id);
		$nodeConfig = $m2->find($node->getCfgId());
		
		//list ( $node, $nodeConfig ) = $m->fetchController ( $id );
		
		$req->setParam ( 'node', $node );
		$req->setParam ( 'nodeConfig', $nodeConfig );
		$req->setControllerName ($nodeConfig->getController());
		$req->setModuleName($nodeConfig->getModule());
		$req->setActionName('load-editor');
		$req->setDispatched ( false );
    }
    public function refreshUrlAction()
    {
    	$result = $this->RefreshUrl();
    	$this->_helper->json ( $result );
    }
    
	public function RefreshUrl() {
		$file = '.htaccess';
		$f = fopen ( $file, 'r+' );
		$contents = fread ( $f, filesize ( $file ) );
		$p1 = strpos ( $contents, '#<list>' );
		$p2 = strpos ( $contents, '#</list>' );
		$result = array ('success' => false, 'msg' => 'Неизвестная ошибка' );
		if ($p1 == false)
			$result = array ('success' => false, 'msg' => 'В файле не установлен #<list>' );
		elseif ($p2 == false)
			$result = array ('success' => false, 'msg' => 'В файле не установлен #</list>' );
		else {
			$m = new Admin_Model_TreeNodeMapper ( );
			$list = $m->fetchURLs ();
			$newcnt = "#<list>\n";
			foreach ( $list as $l ) {
				$u = ($l['URL']{0}=='/') ? substr($l['URL'],1) : $l['URL'];
				//$newcnt .= 'RewriteRule ^' . $u . '/$ index.php?Id=' . $l ['Id'] . " [NC,L]\n";
				$newcnt .= 'RewriteRule ^' . $u . '$ index.php?Id=' . $l ['Id'] . " [NC,L]\n";
			}
			$newcnt .= "#</list>";
			$newcnt = substr ( $contents, 0, $p1 ) . $newcnt;
			$newcnt .= substr ( $contents, $p2 + 8 );
			fseek ( $f, 0 );
			fwrite ( $f, $newcnt );
			ftruncate ( $f, strlen ( $newcnt ) );
			$result = array ('success' => true, 'msg' => 'Список URL обновлен успешно' );
		}
		fclose ( $f );
		return $result;
	}
	
	public function refreshNodesAction(){
		$m = new Admin_Model_TreeNodeMapper();
		$nodes = $m->fetchAll();
		foreach($nodes as $n){
			$n->pack();
			$m->save($n, Admin_Model_TreeNode::getFields());
			$result = array ('success' => true, 'msg' => 'Узлы обновлены успешно' );
		}
		
		$this->_helper->json ( $result );
	}
	
	public function copySubTreeAction(){
		$id = ( int ) $this->getRequest()->getParam ( 'id', 0 );
		$destId = ( int ) $this->getRequest()->getParam ( 'dId', 0 );
		if (($id==0) || ($destId==0))
			throw new Zend_Exception("Не задан идентификаторы копируемого узла и узла назначения");
		$m1 = new Admin_Model_TreeNodeMapper( );
		//echo '/*';
		$m1->copySubTree($id,$destId);
		//echo '*/';
		$result = array ('success' => true, 'msg' => 'Узлы скопированы' );
		$this->_helper->json ( $result );
	}
	
	public function copyNodeAction(){
		$id = ( int ) $this->getRequest()->getParam ( 'id', 0 );
		$destId = ( int ) $this->getRequest()->getParam ( 'dId', 0 );
		if (($id==0) || ($destId==0))
			throw new Zend_Exception("Не задан идентификаторы копируемого узла и узла назначения");
		$m1 = new Admin_Model_TreeNodeMapper();
		$m1->copyNode($id,$destId);
		$result = array ('success' => true, 'msg' => 'Узел скопирован' );
		$this->_helper->json ( $result );
	}
	
	public function moveNodeAction(){
		$id = ( int ) $this->getRequest()->getParam ( 'id', 0 );
		$destId = ( int ) $this->getRequest()->getParam ( 'dId', 0 );
		if (($id==0) || ($destId==0))
			throw new Zend_Exception("Не задан идентификаторы копируемого узла и узла назначения");
		$m1 = new Admin_Model_TreeNodeMapper();
		$m1->moveNode($id,$destId);
		$result = array ('success' => true, 'msg' => 'Узел скопирован' );
		$this->_helper->json ( $result );
	}
}


